import Vue from 'vue'
import Router from 'vue-router'
import iView from 'view-design';
import loader from "./loader"

Vue.use(Router)

const router = new Router({
    routes: [{
        path: '/',
        redirect: '/login'
    }, {
        path: '/login',
        name: 'Login',
        component: () =>
            import ( /* webpackChunkName: "Login" */ '@/views/Login.vue'),
    }]
})

loader(router)

router.beforeEach(async(to, from, next) => {
    iView.LoadingBar.start();

    if (to.name == 'Login') {
        next()
    } else {
        let token = window.localStorage.getItem('token')
        if (!token) {
            router.replace({ name: 'Login' })
        }

        next()
    }
})

router.afterEach(route => {
    iView.LoadingBar.finish();
})

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

export default router